﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Data;
using System.Web;
using System.Web.Mvc;
using System.Configuration;
using Castle.DynamicProxy;
using CNKI.TPI.Web.Base;
using CNKI.TPI.Web.Search.IBLL;
using CNKI.TPI.Web.Search.IDAO;
using CNKI.TPI.Web.Search.Model;
using System.Text.RegularExpressions;
using Microsoft.International.Converters.PinYinConverter;
using CNKI.TPI.Web.Admin.IBLL;//导入拼音

namespace CNKI.TPI.Web.UI.Controllers.Submit
{
    public class SubmitOnlineController : BaseController
    {
        private char separator = Path.DirectorySeparatorChar;
        Dictionary<string, string> dicColunmValues = new Dictionary<string, string>();//数据字典用来存储下拉框级联时的字段名和字段值
        List<SubmitDic> dic = new List<SubmitDic>(); //类对象存储当前字段名和与它级联的字段集合

        int dbID = 0;
        string dbCode = "";
        string dbName = "";
        int Unicode = 0;
        int sysid = -1;

        IFileService fileService = null;
        ISubmitService submitService = null;
        IUserMgmtService userMgmtService = null;
        INaviService naviService = null;
        ISearchService searchService = null;
        ISubmitAdminService submitAdminService = null;

        public SubmitOnlineController(IFileService fileService, ISubmitService submitService, IUserMgmtService userMgmtService, INaviService naviService, ISearchService searchService, ISubmitAdminService submitAdminService)
        {
            this.naviService = this.generator.CreateInterfaceProxyWithTarget<INaviService>(naviService, new IInterceptor[] { new LogInterceptor() });
            this.fileService = this.generator.CreateInterfaceProxyWithTarget<IFileService>(fileService, new IInterceptor[] { new LogInterceptor() });
            this.submitService = this.generator.CreateInterfaceProxyWithTarget<ISubmitService>(submitService, new IInterceptor[] { new LogInterceptor() });
            this.userMgmtService = this.generator.CreateInterfaceProxyWithTarget<IUserMgmtService>(userMgmtService, new IInterceptor[] { new LogInterceptor() });
            this.searchService = generator.CreateInterfaceProxyWithTarget<ISearchService>(searchService, new IInterceptor[] { new LogInterceptor() });
            this.submitAdminService = this.generator.CreateInterfaceProxyWithTarget<ISubmitAdminService>(submitAdminService, new IInterceptor[] { new LogInterceptor() });
        }

        public ActionResult Index()
        {
            //接收参数
            LoadParameter();

            IList<SYS_CMS_SUBMIT> SubmitDB = submitService.GetSubmitConfig(dbCode);//判断验证的表中是否存在数据

            if (SubmitDB.Count > 0)
            {

                string DLName = "";
                string DefaultVaule = "";
                string SelectValue = "";

                //获取数据
                DataTable DT = submitService.GetMetaData(dbID, sysid, string.Join(",", SubmitDB.Select(c => c.FIELDNAME)));
                if (DT.Rows.Count > 0)
                {
                    ViewBag.dtInfo = DT;

                    //获取附件表数据
                    IList<METADATA_FILE> FileInfoList = searchService.GetFile(Convert.ToInt32(sysid), dbCode);
                    if (FileInfoList != null)
                    {
                        ViewBag.FileCount = FileInfoList.Count;
                        ViewBag.FileInfo = FileInfoList;
                    }
                }

                foreach (var item in SubmitDB)
                {
                    DLName = item.FIELDNAME;

                    if (item.FIELDTYPE == 2) //下拉框
                    {
                        DefaultVaule = item.DEFAULTVALUE;
                        SelectValue = DT.Rows.Count == 0 ? "" : DT.Rows[0][DLName].ToString();
                        ViewBag.DLName = SetDropValue(dbCode, DLName, DefaultVaule, SelectValue);//下拉框绑定内容
                    }
                    if (item.FIELDTYPE == 4) //复选框
                    {
                        DefaultVaule = item.DEFAULTVALUE;
                        SelectValue = DT.Rows.Count == 0 ? "" : DT.Rows[0][DLName].ToString();
                        ViewBag.DLName = SetCheckBoxValue(dbCode, DLName, DefaultVaule, SelectValue);//复选框绑定内容
                    }
                }

                ViewBag.dicJson = Newtonsoft.Json.JsonConvert.SerializeObject(dic);//Json赋值--下拉框级联使用
                ViewBag.dicModel = dic;
                ////密级
                string strSecurityValue = "";
                if (DT.Rows.Count > 0)
                {
                    strSecurityValue = DT.Rows[0]["SYS_FLD_SECURITY"].ToString();
                }
                //string Security = ConfigurationManager.AppSettings["Security"].ToString();
                IList<SYS_CMS_SECURITY> SecurityList = userMgmtService.GetSecurity();
                List<SelectListItem> items = new List<SelectListItem>();
                foreach (var item in SecurityList)
                {
                    if (string.IsNullOrEmpty(strSecurityValue) && (item.Value == strSecurityValue.Trim()))
                    {
                        items.Add(new SelectListItem { Text = item.Name, Value = item.Value, Selected = true });
                    }
                    else
                    {
                        items.Add(new SelectListItem { Text = item.Name, Value = item.Value.Trim() });
                    }
                }
                ViewData["密级"] = items;
                //ViewBag.Security = Security;//密级说明


                //附件
                string strFilePath = "";
                string strFileType = "";
                string strDTFlag = "";
                string strFileFieldName = "";
                string FileNum = ConfigurationManager.AppSettings["FileNum"].ToString();
                ViewBag.FileNum = FileNum;  //附件个数
                string FileType = ConfigurationManager.AppSettings["FileType"].ToString();
                ViewBag.FileType = FileType;  //附件类型
                string FileComment = ConfigurationManager.AppSettings["FileComment"].ToString();
                ViewBag.FileComment = FileComment;  //附件说明

                SYS_CMS_DATABASE dbInfo = naviService.GetDatabase(dbCode);
                if (null != dbInfo)
                {
                    Unicode = dbInfo.IsUnicode; //是否小语种
                    strFilePath = dbInfo.FilePath + separator + StringHelper.RemoveHighlightFlag(dbInfo.DatabaseCode) + separator + "Pages";
                    ViewBag.Path = strFilePath;  //附件路径
                    strDTFlag = dbInfo.DatetimeFlag;
                    ViewBag.DTFlag = strDTFlag;  //附件命名时间戳
                    strFileType = dbInfo.PaperType;
                    ViewBag.FileNameType = strFileType;  //附件命名类型（0-原名；1-原名+时间戳；2-获取字段内容命名）
                    if (strFileType == "2")
                    {
                        // 取配置的字段-逗号分隔（比如：班级，学号，姓名）
                        strFileFieldName = dbInfo.PaperFieldValue;
                        ViewBag.FileFieldName = strFileFieldName;
                    }
                }

                try
                {
                    string digitfilename = "";
                    digitfilename = DT.Rows[0]["SYS_FLD_DIGITFILENAME"].ToString(); //附件名称
                    ViewBag.digitfilename = digitfilename;
                }
                catch
                {
                    ViewBag.digitfilename = "";
                }
                return View(SubmitDB);
            }
            else
            {

                ViewBag.alert = "还没有配置此数据库的提交字段，请先配置！";
                ViewBag.Url = Url.Action("index", "Submit");
                return PartialView("_JsAlertUrl");
            }
        }


        private void LoadParameter()
        {
            if (!String.IsNullOrEmpty(Request["dbCode"]))
            {
                dbCode = Request["dbCode"];
                ViewBag.dbCode = dbCode;
                SYS_CMS_DATABASE dbInfo = naviService.GetDatabase(dbCode);
                if (dbInfo != null)
                {
                    dbID = dbInfo.SysID;
                    ViewBag.dbID = dbID;
                }
            }
            if (!String.IsNullOrEmpty(Request["sysid"]))
            {
                sysid = int.Parse(Request["sysid"]);
                ViewBag.sysid = sysid;
            }
            else
            {
                ViewBag.sysid = "-1";
            }

            //获取汉字拼音配置
            string strHzToPy = submitService.GetPYHZList(dbCode);
            if (string.IsNullOrEmpty(strHzToPy))
            {
                ViewBag.dicPYHZ = strHzToPy;
            }

            if (!String.IsNullOrEmpty(Request["displayDBName"]))
            {
                dbName = Server.UrlDecode(Request["displayDBName"].ToString());
                ViewBag.dbName = dbName;
            }

            ViewBag.ReturnUrl = Request.Url.ToString();

        }

        /// <summary>
        /// 根据默认值构造下拉框的选择内容
        /// </summary>
        /// <param name="strdbCode">数据库code</param>
        /// <param name="strFieldName">字段名</param>
        /// <param name="strDefaultValue">配置提交时下拉的内容列表：用逗号隔开的值或者是一个sql语句</param>
        /// <param name="strSelectValue">数据库中的值</param>
        /// <returns></returns>
        #region 根据默认值构造下拉框的选择内容
        private SelectList SetDropValue(string strdbCode, string strFieldName, string strDefaultValue, string strSelectValue)
        {
            if (strDefaultValue.Length <= 0)
            {
                return null;
            }
            // 判断是否是sql语句
            string strTempDefaultValue = strDefaultValue.ToLower().Trim();
            if (strTempDefaultValue.IndexOf("select") == 0) // 是sql语句的情况
            {
                //存储字段名称集合
                List<string> ColumnNames = new List<string>();

                //递归调用获得下拉框绑定的sql语句，并且存储级联字段
                strDefaultValue = this.GetSqlCode(strdbCode, strDefaultValue, strFieldName, strSelectValue, ref ColumnNames, ref dicColunmValues);
                DataTable dt = submitService.ExecuteSql(strDefaultValue.Trim());
                if (dt == null || dt.Rows.Count <= 0)
                {
                    return null;
                }
                else
                {
                    //如果为空，默认第一个选中
                    if (strSelectValue.Trim().Length <= 0)
                    {
                        strSelectValue = dt.Rows[0][0].ToString();
                    }
                    List<SelectListItem> items = new List<SelectListItem>();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        if (dt.Rows[i][0].ToString().Trim() == strSelectValue.Trim())
                        {
                            items.Add(new SelectListItem { Text = dt.Rows[i][0].ToString().Trim(), Value = dt.Rows[i][0].ToString().Trim(), Selected = true });
                        }
                        else
                        {
                            items.Add(new SelectListItem { Text = dt.Rows[i][0].ToString().Trim(), Value = dt.Rows[i][0].ToString().Trim() });
                        }
                    }
                    var selectlist = new SelectList(items);
                    ViewData[strFieldName] = items;

                    //添加字典内容
                    SubmitDic sd = new SubmitDic()
                    {
                        columnName = strFieldName,
                        parentColumnName = ColumnNames,
                        dicColunmValues = dicColunmValues
                    };
                    dic.Add(sd);

                    return selectlist;
                }
            }
            else // 是用逗号隔开的值
            {
                string[] strArrDefaultValue = strDefaultValue.Split(new char[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
                if (strSelectValue.Trim().Length <= 0) //如果为空，默认第一个选中
                {
                    strSelectValue = strArrDefaultValue[0];
                }
                List<SelectListItem> items = new List<SelectListItem>();
                for (int i = 0; i < strArrDefaultValue.Length; i++)
                {
                    if (strArrDefaultValue[i] == strSelectValue)
                    {
                        items.Add(new SelectListItem { Text = strArrDefaultValue[i], Value = strArrDefaultValue[i], Selected = true });
                    }
                    else
                    {
                        items.Add(new SelectListItem { Text = strArrDefaultValue[i], Value = strArrDefaultValue[i] });
                    }
                }
                var selectlist = new SelectList(items);
                ViewData[strFieldName] = items;
                return selectlist;
            }
        }
        #endregion


        /// <summary>
        /// 根据默认值构造复选框绑定内容
        /// </summary>
        /// <param name="strdbCode">数据库code</param>
        /// <param name="strFieldName">字段名</param>
        /// <param name="strDefaultValue">配置提交时复选框内容(用逗号隔开的字符串)</param>
        /// <param name="strSelectValue">默认选择的值(用逗号隔开的字符串)</param>
        /// <returns></returns>
        #region 根据默认值构造复选框绑定内容
        private SelectList SetCheckBoxValue(string strdbCode, string strFieldName, string strDefaultValue, string strSelectValue)
        {
            if (strDefaultValue.Length <= 0)
            {
                return null;
            }
            string[] strArrDefaultValue = strDefaultValue.Split(new char[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);
            if (strSelectValue.Trim().Length <= 0)//如果为空，默认第一个选中
            {
                //strSelectValue = "," + strArrDefaultValue[0].ToString() + ",";
            }
            else
            {
                strSelectValue = "," + strSelectValue + ",";
            }
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < strArrDefaultValue.Length; i++)
            {
                if (strSelectValue.IndexOf("," + strArrDefaultValue[i] + ",") >= 0)
                {
                    items.Add(new SelectListItem { Text = strArrDefaultValue[i], Value = strArrDefaultValue[i], Selected = true });
                }
                else
                {
                    items.Add(new SelectListItem { Text = strArrDefaultValue[i], Value = strArrDefaultValue[i] });
                }
            }
            var selectlist = new SelectList(items);
            ViewData[strFieldName] = items;
            return selectlist;
        }
        #endregion

        /// <summary>
        /// 递归实现
        /// </summary>
        /// <param name="strdbCode">数据库code</param>
        /// <param name="sqlCondition">sql语句</param>
        /// <param name="strFieldName">字段名</param>
        /// <param name="strSelectValue">数据库中的值</param>
        /// <param name="ColumnNames">相关联的上级字段</param>
        /// <param name="ColumnNameValues">相关联的上级字段值</param>
        /// <returns></returns>
        #region 递归实现
        private string GetSqlCode(string strdbCode, string sqlCondition, string strFieldName, string strSelectValue, ref List<string> ColumnNames, ref  Dictionary<string, string> dicColunmValues)
        {
            string strDefaultValue = sqlCondition;
            //用正则规则来截取：###和）之间的内容值 (括号需要转义-\))
            //1.SELECT 学院 FROM EMPTY2_METADATA WHERE (EMPTY2_METADATA.学院=*) GROUP BY 学院 ORDER BY 学院 
            //2.SELECT 系 FROM EMPTY2_METADATA WHERE (EMPTY2_METADATA.学院=###学院) GROUP BY 系 ORDER BY 系   
            //3.SELECT 班级 FROM EMPTY2_METADATA WHERE (EMPTY2_METADATA.学院=###学院) and (EMPTY2_METADATA.系=###系) GROUP BY 班级 ORDER BY 班级）
            var listArray = StringHelper.GetMidLine(sqlCondition, @"###.*?(?=\))");
            //获得字段值
            if (!String.IsNullOrEmpty(strSelectValue))
            {
                //字典添加内容
                if (!dicColunmValues.Keys.Contains(strFieldName))
                {
                    //key-相关联的上级字段名，value-相关联的上级字段值
                    dicColunmValues.Add(strFieldName, strSelectValue);
                }
            }
            foreach (var item in listArray)
            {
                // 获得字段名称
                string strRegField = item.Replace("###", "");
                if (!ColumnNames.Contains(strRegField))
                {
                    ColumnNames.Add(strRegField); //相关联的上级字段名集合保存在list中
                }

                // 获得涉及到的字段具体的值，通过Sql语句去数据库中查找值
                SYS_CMS_SUBMIT submitInfo = submitService.GetSubmitConfig(strdbCode, strRegField, SubmitFieldType.ComboBox);
                if (null != submitInfo)
                {
                    sqlCondition = submitInfo.DEFAULTVALUE;

                    if (sqlCondition.IndexOf("###") >= 0)
                    {
                        //递归调用
                        sqlCondition = this.GetSqlCode(strdbCode, sqlCondition, strFieldName, strSelectValue, ref ColumnNames, ref dicColunmValues);
                    }


                    DataTable dtTemp = submitService.ExecuteSql(sqlCondition.Trim());
                    if (dtTemp != null && dtTemp.Rows.Count > 0)
                    {
                        if (dicColunmValues.Count == 0)
                        {
                            //提交
                            string strTempValue = dtTemp.Rows[0][0].ToString().Trim();
                            if (!String.IsNullOrEmpty(strSelectValue))
                            {
                                strTempValue = strSelectValue;
                            }
                            if (strTempValue.Length > 0)
                            {
                                strDefaultValue = strDefaultValue.Replace("###" + strRegField, "'" + strTempValue + "'");
                            }
                        }
                        else
                        {
                            //更新
                            foreach (string key in dicColunmValues.Keys)
                            {
                                if (key == strRegField)
                                {
                                    strDefaultValue = strDefaultValue.Replace("###" + strRegField, "'" + dicColunmValues[key] + "'");
                                }
                            }
                        }
                    }
                }
            }
            return strDefaultValue;
        }
        #endregion


        /// <summary>
        /// 下拉框级联的onchange调用的方法
        /// </summary>
        /// <param name="dbcode">数据库code</param>
        /// <param name="CurName">当前的字段名</param>
        /// <param name="pareVaue">相关联的上级字段名与值（字段1:字段1内容，字段2:字段2内容，字段3:字段3内容）</param>
        /// <returns></returns> 
        #region 下拉框级联的onchange调用的方法
        public JsonResult GetSubject(string dbcode, string CurName, string pareVaue)
        {
            // 获得涉及到的字段具体的值，通过Sql语句去数据库中查找值
            string strSql = "";
            SYS_CMS_SUBMIT submitInfo = submitService.GetSubmitConfig(dbcode, CurName, SubmitFieldType.ComboBox);
            if (null != submitInfo)
            {
                strSql = submitInfo.DEFAULTVALUE;
            }

            //SELECT 班 FROM EMPTY2_METADATA,EMPTY2_METADATA WHERE (EMPTY2_METADATA.学院=###院系) AND (EMPTY2_METADATA.系=###专业) GROUP BY 班 ORDER BY 班	
            string[] ArrPareVaue = pareVaue.Split(new char[] { ',', '，' }, StringSplitOptions.None);
            for (int i = 0; i < ArrPareVaue.Length; i++)
            {
                if (!String.IsNullOrEmpty(ArrPareVaue[i]))
                {
                    strSql = strSql.Replace("###" + ArrPareVaue[i].Split(':')[0].ToString(), "'" + ArrPareVaue[i].Split(':')[1].ToString() + "'"); // 替换sql语句相应的部分
                }
            }
            DataTable dt = submitService.ExecuteSql(strSql);
            List<SelectListItem> items = new List<SelectListItem>();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                items.Add(new SelectListItem { Text = dt.Rows[i][0].ToString().Trim(), Value = dt.Rows[i][0].ToString().Trim() });
            }
            return Json(items, JsonRequestBehavior.AllowGet);
        }
        #endregion


        /// <summary>
        /// 上传附件
        /// </summary>
        /// <param name="fPath"></param>
        /// <returns></returns>
        #region 上传附件
        [AllowAnonymous]
        public JsonResult FileUpload(string fPath, string fType, string fFielValue, string dtFlag, string fName, int sysid, string dbcode)
        {
            var httpfile = System.Web.HttpContext.Current.Request.Files[0];
            if (httpfile == null || httpfile.ContentLength == 0)
            {
                return null;
            }
            string fileName = httpfile.FileName;//全文件名
            string extraName = httpfile.FileName.Substring(httpfile.FileName.LastIndexOf(".") + 1); //后缀
            string fileNameWithoutExt = httpfile.FileName.Substring(0, httpfile.FileName.LastIndexOf(".")); //文件名

            // 根据数字对象命名设置改变附件名称
            if (fType == "1")
            {
                //PAPERTYPE＝1-原始文件名+时间戳
                fileName = fileNameWithoutExt + DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "") + "." + extraName;
            }
            else if (fType == "2")
            {
                // 获取具体的值
                string strFileName = "";
                string[] ArrFieldValue = fFielValue.Split(new char[] { ',', '，' }, StringSplitOptions.RemoveEmptyEntries);

                for (int i = 0; i < ArrFieldValue.Length; i++)
                {
                    strFileName += ArrFieldValue[i].ToString();
                }

                string strDateTimeFlag = dtFlag;
                if (strDateTimeFlag == "1")
                {
                    strFileName += DateTime.Now.ToString().Replace("-", "").Replace(":", "").Replace(" ", "").Replace("/", "");
                }

                //★上传时判断原文件名是否有_16的字符串
                if (fileName.IndexOf("_16") > 0)
                {
                    strFileName += "_16";
                }
                fileName = strFileName + "." + extraName;
            }

            //判断上传附件是否存在
            string message = "";
            string result = "False";
            if (!String.IsNullOrEmpty(fName))
            {
                if (fName.IndexOf("|") >= 0)
                {
                    string[] ArrFile = fName.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                    for (int i = 0; i < ArrFile.Length; i++)
                    {
                        if (ArrFile[i].ToString().ToLower() == fileName.ToLower())
                        {
                            result = "True";
                            message = "附件已经存在，请先删除！";
                            return Json(new { r = result, m = message }, JsonRequestBehavior.AllowGet);
                        }
                    }
                }
                else
                {
                    if (fName.ToLower() == fileName.ToLower())
                    {
                        //Content("<script >alert(’附件已经存在，请先删除!’);</script >", "text/html");
                        result = "True";
                        message = "附件已经存在，请先删除！";
                        return Json(new { r = result, m = message }, JsonRequestBehavior.AllowGet);
                    }
                }
            }

            if (submitService.CheckFileExsit(sysid, dbcode, fileName))
            {
                result = "True";
                message = " 附件已经存在！";
                return Json(new { r = result, m = message }, JsonRequestBehavior.AllowGet);
            }

            //文件路径
            fPath = fPath + separator + fileService.GetDirByName(fileName);
            string SaveAllAsPath = fPath + separator + fileName;

            //if (!System.IO.Directory.Exists(fPath))
            //{
            //    创建文件夹
            //    File_Oper.CreateDirectory(fPath);
            //    去掉文件夹的只读属性
            //    System.IO.DirectoryInfo DirInfo = new DirectoryInfo(fPath);
            //    DirInfo.Attributes = FileAttributes.Normal & FileAttributes.Directory;
            //}

            string filepath = fPath + separator + fileName;
            LogOpr.Debug("UploadFilePath=" + filepath);
            bool status = submitService.SaveFile(httpfile, filepath);
            if (!status)
            {
                result = "True";
                message = "上传失败！";
                return Json(new { r = result, m = message }, JsonRequestBehavior.AllowGet);
            }
            //try
            //{
            //    httpfile.SaveAs(filepath); //保存文件
            //}
            //catch (Exception ex)
            //{
            //    LogOpr.Error(ex.ToString());
            //    result = "True";
            //    message = "上传失败！" + ex.Message;
            //    return Json(new { r = result, m = message }, JsonRequestBehavior.AllowGet);
            //}

            string path = filepath;
            string type = extraName;
            MFileInfo mf = new MFileInfo
            {
                FileName = fileName,
                ExtraName = extraName,
                FilePath = filepath,
                FileSize = httpfile.ContentLength
            };
            return Json(mf, JsonRequestBehavior.AllowGet);
        }
        #endregion

        /// <summary>
        /// 删除附件
        /// </summary>
        /// <param name="fPath"></param>
        /// <returns></returns>
        #region 删除附件
        [AllowAnonymous]
        public string FileDelete(string dbcode, string filepath, string filename, string digitfilename, string sysid)
        {
            string result = "False";
            try
            {
                string strSavePath = filepath + separator + fileService.GetDirByName(filename) + separator + filename;
                //if (System.IO.File.Exists(strSavePath))
                //{
                //    FileInfo fi = new FileInfo(strSavePath);
                //    //判断当前文件属性是否是只读  
                //    if (fi.Attributes.ToString().IndexOf("ReadyOnly") >= 0)
                //    {
                //        fi.Attributes = FileAttributes.Normal;
                //        result = digitfilename;
                //    }

                //    if (sysid == "-1")
                //    {
                //        //删除实体附件 
                //        try
                //        {
                //            System.IO.File.Delete(strSavePath);
                //        }
                //        catch
                //        {

                //        }
                //        result = StringHelper.removeStr(digitfilename, filename);
                //    }
                //    else
                //    {
                //        result = submitService.DeleteFileInfo(dbcode, filename, digitfilename, int.Parse(sysid), result, strSavePath);
                //    }
                //}

                if (sysid == "-1")
                {
                    //删除实体附件
                    submitService.DeleteFile(strSavePath);
                    result = StringHelper.removeStr(digitfilename, filename);
                }
                else
                {
                    result = submitService.DeleteFileInfo(dbcode, filename, digitfilename, int.Parse(sysid), result, strSavePath);
                }
            }
            catch (Exception ex)
            {
                LogOpr.Error(ex.ToString());
            }

            return "[{\"result\":\""+result+"\"}]";
        }


        #endregion
        /// <summary> 
        /// 汉字转化为拼音
        /// </summary> 
        /// <param name="str">汉字</param> 
        /// <returns>全拼</returns> 
        private string GetPinyin(string hz)
        {
            string py = string.Empty;
            foreach (char obj in hz)
            {
                try
                {
                    ChineseChar chineseChar = new ChineseChar(obj);
                    string t = chineseChar.Pinyins[0].ToString();
                    py += t.Substring(0, t.Length - 1);
                }
                catch
                {
                    py += obj.ToString();
                }
            }
            return py;
        }

        /// <summary> 
        /// 汉字转化为拼音进行处理
        /// </summary> 
        /// <param name="str">汉字</param> 
        /// <returns>全拼</returns> 
        public ActionResult GetPinyinByHz(string source)
        {
            string result = string.Empty;    // 转拼音的结果
            string temp = string.Empty;     // 下面foreach用到的临时变量
            if (null != source)
            {
                foreach (char item in source)   // 遍历每个源字符
                {
                    temp = GetPinyin(item.ToString());  // 将每个字符转拼音
                    // 处理：获取首字母大写、其余字母小写
                    result += (String.Format("{0}{1} ", temp.Substring(0, 1).ToUpper(), temp.Substring(1).ToLower()));
                }
            }
            return Content(result);
        }


        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult SubmitSave(string ReturnUrl = "")
        {
            string cid = "-1";
            string result = "False";
            string message = "";
            bool blSave = false;
            bool isUnicode = Unicode == 1 ? true : false;
            int nInsertRows = 0;

            //接收参数
            LoadParameter();
            //this.Request.Form.AllKeys.AsEnumerable();

            Dictionary<string, object> InfoList = new Dictionary<string, object>();

            IList<SYS_CMS_SUBMIT> SubmitDB = submitService.GetSubmitConfig(dbCode);
            foreach (var item in SubmitDB)
            {
                //必填字段检验
                if (item.ISALLOWNULL == 1)
                {
                    if (String.IsNullOrEmpty(Request.Form[item.FIELDNAME]))
                    {
                        message = "对不起，" + item.FIELDDISPLAYNAME + "字段为必填字段，请填写！";
                        return Json(new { c = cid, r = result, m = message }, JsonRequestBehavior.AllowGet);
                    }
                }
                // 唯一性检验
                if (item.ISONLYONE == 1)
                {
                    if (!submitService.IsOnlyOne(dbCode, sysid, item.FIELDNAME, Request.Form[item.FIELDNAME].ToString()))
                    {
                        message = "对不起，" + item.FIELDDISPLAYNAME + "字段的值：" + Request.Form[item.FIELDNAME].ToString().Trim() + "已经存在，请重新填写！";
                        return Json(new { c = cid, r = result, m = message }, JsonRequestBehavior.AllowGet);
                    }
                }
                //InfoList.Add(item.FIELDNAME, StringHelper.ConvertStr(Request.Form[item.FIELDNAME] == null ? "" : Request.Form[item.FIELDNAME].ToString().Trim()));
                InfoList.Add(item.FIELDNAME, Request.Form[item.FIELDNAME] == null ? "" : Request.Form[item.FIELDNAME].ToString().Trim());

            }
            InfoList.Add("SYS_FLD_SECURITY", Request.Form["密级"].ToString().Trim());
            try
            {
                //int newSysid = 0;
                int flag = -1;


                //保存数据
                if (sysid == -1)
                {
                    //插入主表数据
                    sysid = searchService.InsertMetaData(dbCode, InfoList);
                    //newSysid = sysid;
                    if (sysid > 0)
                    {
                        blSave = true;
                    }
                }
                else
                {
                    flag = 0;
                    //更新数据
                    blSave = searchService.UpdateMetaData(sysid.ToString(), dbCode, InfoList);
                    //newSysid = searchService.InsertMetaData(dbCode, InfoList);
                    if (sysid > 0)
                    {
                        blSave = true;
                    }
                }

                //处理附件表数据
                if (blSave)
                {
                    int nUpdate = 0;
                    string resorceType = "T"; // 附件类型
                    int contentType = 0; // 附件内容类型
                    //string strUploadUserName = ""; // 论文提交的话不考虑用户
                    string strUploadTime = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); // 上传时间
                    int readOnline = 0;
                    int contentFlag = 0;
                    string filename = Request.Form["FileName"]; //上传文件名
                    string filesize = Request.Form["FileLength"];//文件大小
                    string fileformat = Request.Form["FileFormart"];//文件格式
                    string filepath = Request.Form["FilePath"];//文件路径
                    string digitfilename = Request.Form["digitfilename"];//数据库中文件名
                    string path = Request.Form["Path"];//数据库中文件名

                    string SpanFileName = Request.Form["SpanFileName"];
                    string SpanFileSysid = Request.Form["SpanFileSysid"];
                    if (SpanFileName != "")
                    {
                        if (SpanFileName.IndexOf(',') > 0)
                        {
                            string[] arrayName = SpanFileName.Split(',');
                            string[] arraySysid = SpanFileSysid.Split(',');
                            for (var i = 0; i < arrayName.Length; i++)
                            {
                                if (filename.IndexOf(arrayName[i]) < 0)
                                {
                                    FileDelete(dbCode, path, arrayName[i], digitfilename, sysid.ToString());
                                }
                            }
                        }
                        else
                        {
                            if (filename.IndexOf(SpanFileName) < 0)
                            {
                                FileDelete(dbCode, path, SpanFileName, digitfilename, sysid.ToString());
                            }
                        }
                    }
                    nUpdate = submitService.ProcessMetaDataFile(dbCode, isUnicode, sysid, resorceType, contentType, readOnline, contentFlag, filename, filesize, fileformat, filepath, digitfilename, flag);
                    //nUpdate = submitService.UpdateMetaFileLink(dbCode, sysid, newSysid);
                    //if (flag == 0)
                    //{
                    //    bool status = submitAdminService.DelMetaData(dbCode, sysid);
                    //    if (status)
                    //    {
                    //        nUpdate = 1;
                    //    }
                    //}

                    if (nUpdate > 0)
                    {
                        message = "保存信息成功！";
                        result = "True";
                        return Json(new { c = nInsertRows, r = result, m = message, f = filename }, JsonRequestBehavior.AllowGet);
                    }
                    else
                    {
                        message = "保存信息失败！";
                        return Json(new { c = nInsertRows, r = result, m = message }, JsonRequestBehavior.AllowGet);
                    }
                }
                else
                {
                    message = "保存信息失败！";
                    return Json(new { c = cid, r = result, m = message }, JsonRequestBehavior.AllowGet);
                }

            }
            catch (Exception ex)
            {
                message = "保存信息失败！" + ex.Message;
                LogOpr.Error(ex.ToString());
                return Json(new { c = cid, r = result, m = message }, JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 判断词字段是否是导航字段
        /// </summary>
        /// <param name="dbcode">数据库code</param>
        /// <param name="filename">字段名</param>
        /// <returns></returns>
        public string GetNavi(string dbCode, string ClsFieldName)
        {

            string result = "False";
            //string ClsTable = dbCode + "_CLS";
            //string strSql = "select count(*) from " + ClsTable + " where EXPRESSION ='" + ClsFieldName + "'";
            //int nIsExist = userDBDAO.GetDataCount(strSql);
            int nIsExist = naviService.GetClsID(dbCode, ClsFieldName);
            if (nIsExist > 0)
            {
                result = "True";
            }
            return result;
        }

    }
}
